package com.yc.qunxing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yc.qunxing.entity.Users;
import com.yc.qunxing.mapper.UsersMapper;
import com.yc.qunxing.result.Result;
import com.yc.qunxing.service.IUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 鹏哥
 * @since 2024-05-23
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {

    @Autowired
    private UsersMapper usersMapper;

    @Override
    public Result<String> registerUser(Users users) {
        if (StringUtils.isEmpty(users.getUsername()) || StringUtils.isEmpty(users.getPassword())) {
            return Result.error("用户名和密码不能为空");
        }
        if (StringUtils.isEmpty(users.getEmail()) || StringUtils.isEmpty(users.getPhoneNumber())) {
            return Result.error("手机号和邮箱不能为空");
        }
        // 判断用户名是否已存在
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("username", users.getUsername());
        Users existingUser = baseMapper.selectOne(wrapper);
        if (existingUser != null) {
            return Result.error("用户名已存在");
        }
        users.setCreatedAt(LocalDate.now());
        users.setStatus("1");
        // 保存用户信息
        boolean saved = save(users);
        if (saved) {
            return Result.success("注册成功");
        } else {
            return Result.error("注册失败");
        }
    }

    @Override
    public void updateRaffleNum(Integer id) {
        // 执行更新操作，将 raffleNum 减一
        usersMapper.update(null,
                Wrappers.<Users>lambdaUpdate()
                        .setSql("raffle_num = raffle_num - 1")
                        .eq(Users::getId, id)
        );
    }
    @Override
    public boolean verifyOriginalPassword(Integer userId, String originalPassword) {
        Users user = usersMapper.selectById(userId);
        return user != null && user.getPassword().equals(originalPassword);
    }

    @Override
    public boolean changePassword(Integer userId, String newPassword) {
        Users user = new Users();
        user.setId(userId);
        user.setPassword(newPassword);
        return usersMapper.updateById(user) == 1;
    }

    @Override
    public boolean changePhone(Integer userId, String phone) {
        Users user = new Users();
        user.setId(userId);
        user.setPhoneNumber(phone);
        return usersMapper.updateById(user) == 1;
    }

    @Override
    public boolean changeName(Integer userId, String name) {
        Users user = new Users();
        user.setId(userId);
        user.setUsername(name);
        return usersMapper.updateById(user) == 1;
    }

    @Override
    public List<Users> getUserByManager(String keyword, String keywordOrder) {
        QueryWrapper<Users> queryWrapper=new QueryWrapper();
        if(keyword!=null && !keyword.isEmpty()){
            queryWrapper.and(wrapper-> wrapper
                    .like("id", keyword));
        }
        if (keywordOrder != null && !keywordOrder.isEmpty()) {
            queryWrapper.like("status", keywordOrder);
        }
        queryWrapper.orderByDesc("created_at");
        return usersMapper.selectList(queryWrapper);
    }

    @Resource
    private JavaMailSender mailSender;

    @Override
    public boolean sendVerificationCode(Integer userId, String email, String code) {
         String to=email;
        String subject="群星网约车官方验证码";
        String content=code;
        SimpleMailMessage message=new SimpleMailMessage();
        message.setFrom("936482013@qq.com");
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        mailSender.send(message);
        System.out.println("Sending verification code " + code + " to email " + email);
        return true;
    }

    @Override
    public boolean changeEmail(Integer userId, String newEmail) {
        Users user = new Users();
        user.setId(userId);
        user.setEmail(newEmail);
        return usersMapper.updateById(user) == 1;
    }
}
